package com.zdsoft.site.mina.client;

import java.net.InetSocketAddress;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zdsoft.site.mina.server.HimiObject;

public class ObjectClientHanlder extends IoHandlerAdapter  {
	
	private static Logger logger=LoggerFactory.getLogger(ObjectClientHanlder.class);
    private static final int PORT = 8015;
	// 当一个客端端连结到服务器后
	@Override
	public void sessionOpened(IoSession session) throws Exception {
		logger.debug("sessionOpened");
		HimiObject ho = new HimiObject(1,"clientHimi");
		session.write(ho);
		
	}
	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		HimiObject ho = (HimiObject) message;
		logger.debug("发送消息到服务器.{}",ho.toString());
	}
	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		// // 我们己设定了服务器解析消息的规则是一行一行读取,这里就可转为String:
		// String s = (String) message;
		// // Write the received data back to remote peer
		// logger.debug("收到客户机发来的消息: " + s);
		// // 测试将消息回送给客户端 session.write(s+count); count++;
		HimiObject ho = (HimiObject) message;
		logger.debug("接收从服务器返回的消息:{}",ho.toString());
		//session.write(ho);
	}
	public static void main(String[] args) {
		// 创建一个tcp/ip 连接
		NioSocketConnector connector = new NioSocketConnector();
		/*---------接收字符串---------*/
		// //创建接收数据的过滤器
		// DefaultIoFilterChainBuilder chain = connector.getFilterChain();
		// // 设定这个过滤器将一行一行(/r/n)的读取数据
		// chain.addLast("myChin", new ProtocolCodecFilter(
		// new TextLineCodecFactory()));
		/*---------接收对象---------*/
		// 创建接收数据的过滤器
		DefaultIoFilterChainBuilder chain = connector.getFilterChain();
		// 设定这个过滤器将以对象为单位读取数据
		ProtocolCodecFilter filter = new ProtocolCodecFilter(
				new ObjectSerializationCodecFactory());
		// 设定服务器端的消息处理器:一个SamplMinaServerHandler对象,
		chain.addLast("objectFilter",filter);

		// 设定服务器端的消息处理器:一个 SamplMinaServerHandler 对象,
		connector.setHandler(new ObjectClientHanlder());
		// Set connect timeout.
		connector.setConnectTimeoutCheckInterval(30);
		// 连结到服务器:
		ConnectFuture cf = connector.connect(new InetSocketAddress("localhost",PORT));
		// Wait for the connection attempt to be finished.
		cf.awaitUninterruptibly();
		cf.getSession().getCloseFuture().awaitUninterruptibly();
		connector.dispose();
	}
}
